<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <!-- 最长理想子序列 -->
    <script>
      function longestIdealString(s, k) {
        let n = s.length
        let arr = new Array(26).fill(0) // arr[i]为以'abc...z'[i]结尾的子序列最大长度
        for (let i = 0; i < n; i++) {
          let code = s.charCodeAt(i) - 'a'.charCodeAt(0)
          let max = 0
          // [0,i)区间的子序列结尾的字母如果符合条件，则比较大小，选出最长的加上当前字符长度即可
          for (let j = Math.max(0, code - k); j <= Math.min(25, code + k); j++) {
            max = Math.max(max, arr[j])
          }
          arr[code] = max + 1
        }
        return Math.max(...arr) // 从不同字母结尾的字符串中找到最长的
      }
      console.log(longestIdealString('acfgbd', 2))
    </script>
  </body>
</html>
